package utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 */
public class CheckAppInstalledUtil {

	/**
	 * 判断 APP 是否安装
	 *
	 * @param context     活动对应的上下文对象
	 * @param packageName 需要检查的应用包名
	 * @return
	 */
	public static boolean isInstalled(Context context, String packageName) {
		try {
			Process process = Runtime.getRuntime().exec("pm list package -3");
			BufferedReader bis = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = null;
			while ((line = bis.readLine()) != null) {
				System.out.println("MainActivity.runCommand, line=" + line.substring(8,line.length()));
				if (packageName.equals(line.substring(8,line.length()))) {
					return true;
				}
			}
		} catch (IOException e) {
			System.out.println("MainActivity.runCommand,e=" + e);
		}
		return false;
	}

	private void runCommand() {
		try {
			Process process = Runtime.getRuntime().exec("pm list package -3");
			BufferedReader bis = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = null;
			while ((line = bis.readLine()) != null) {
				System.out.println("MainActivity.runCommand, line=" + line);
			}
		} catch (IOException e) {
			System.out.println("MainActivity.runCommand,e=" + e);
		}
	}

	/**
	 * 打开或者去下载应用
	 *
	 * @param context     活动对应上下文对象
	 * @param packagename 需要打开的应用包名
	 */
	public static void openApp(Activity context, String packagename) {

		try {
			PackageManager packageManager = context.getPackageManager();
			Intent	intent =packageManager.getLaunchIntentForPackage(packagename);
			context.startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}


	}
}
